<?php

namespace App\Events;

use App\Models\GameRecord;
use App\Models\Machine;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MachineStatusChanged implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    protected $machine;
    protected $record;
    
    /**
     * 创建一个新的事件实例
     *
     * @param \App\Models\Machine $machine
     * @param \App\Models\GameRecord $record
     * @return void
     */
    public function __construct(Machine $machine, GameRecord $record = null)
    {
        $this->machine = $machine;
        
        $this->record = $record;
    }

    /**
     * 指定事件在哪些频道上进行广播
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('machines.' . $this->machine->id);
    }
    
    /**
     * 事件名
     *
     * @return string
     */
    public function broadcastAs()
    {
        return snake_case(class_basename(self::class), '.');
    }
    
    /**
     * 事件参数
     *
     * @return array
     */
    public function broadcastWith()
    {
        $player = null;
        $gameRecord = null;
        
        if ($this->machine->isWorking()) {
            $user = $this->machine->latestUser;
            
            $player = [
                'avatar' => image_url($user->avatar),
                'nickname' => $user->nickname,
            ];
        }
        
        if ($this->record) {
            $gameRecord = [
                'id' => $this->record->id,
                'operate_result' => $this->record->operate_result,
            ];
        }
        
        event(new SpectatorsChanged($this->machine));
        
        return [
            'device_status' => $this->machine->device_status,
            'player' => $player,
            'game_record' => $gameRecord,
        ];
    }
}
